<?php
/**
 * 这个是存储和读取模板消息的 formids 操作类
 */
class mnshelper{
  //关键代码
    public $uniacid = 0;
    public $openid = 0;
    /**
     * 构造一个 小程序formsid 的缓存类
     * @global type $_W
     * @global type $_GPC
     */
    public function __construct() {
        global $_W,$_GPC;
        $this->uniacid = $_W['uniacid'];
        $this->openid  = $_W['openid'];
    }
    /**
     * 
     * @param type $openId
     * @param type $formIds
     */
    public function saveFormIds($openId, $formIds){
         
        if($formIds){            
            $data = json_decode( htmlspecialchars_decode($formIds) ,TRUE);//JSON解码为数组   
        
            $this -> _saveFormIdsArray($openId,$data);//保存
        }
    }
    /**
     * 
     * @param type $openId
     * @return boolean
     */
    private function _get($openId){
        
        $data = pdo_fetchcolumn("select formids from ".tablename('kbwdl_formids')." where uniacid='{$this->uniacid}' and openid='{$openId}'");
        if($data)return json_decode($data,TRUE);
        else return FALSE;
    }
    /**
     * 
     * @param type $openId
     * @param type $data
     * @return type
     */
    private function _save($openId,$data){
        $has = pdo_fetchcolumn("select id from ".tablename('kbwdl_formids')." where uniacid='{$this->uniacid}' and openid='{$openId}'");
        if(! $has){
            return pdo_insert("kbwdl_formids", array('openid'=>$openId, 'uniacid'=>$this->uniacid,'formids'=>json_encode($data)));
        }else{
           return pdo_update("kbwdl_formids", array('formids'=>json_encode($data)), array(
             'openid'=>$openId, 'uniacid'=>$this->uniacid   
           ) ); 
        }
       
    }
    private function _saveFormIdsArray($openId,$arr){
        $res = $this->_get($openId);
        if($res){
            $new = array_merge($res, $arr);//合并数组
            return $this->_save($openId,$new);
        }else{
            $result = $arr;
            return $this->_save($openId,$result);
        }
    }

    /**
     * 取出一个可用的用户openId对应的推送码
     * @param type $openId
     * @return boolean
     */
    public function getFormId($openId){
        $res = $this->_get($openId);
        if($res){
            if(!count($res)){
                return FALSE;
            }
            $newData = array();
            $result = FALSE;
            for($i = 0;$i < count($res);$i++){
                if($res[$i]['expire'] > time()){
                    $result = $res[$i]['formId'];//得到一个可用的formId
                    for($j = $i+1;$j < count($res);$j++){//移除本次使用的formId
                        array_push($newData,$res[$j]);//重新获取可用formId组成的新数组
                    }
                    break;
                }
            }
               $this->_save($openId,$newData);
                return $result;
            }else{
                return FALSE;
            }
    }
     public function send_template_notice($openid, $page='',$form_id, $data=array())
    { 
        global $_GPC, $_W;
        $uniacid = $data['uniacid'];
        load()->func('communication');     
        /*获取公众号access_token*/
        load()->classs('wxapp.account');
        if(empty($openid) || empty($form_id) ){
            return ;
        }
        $account = pdo_fetch('select * from '.  tablename('account_wxapp'). " where acid= '".$uniacid ."'" );       
        $accObj= new WxappAccount( $account);        
        $ACCESS_TOKEN = $accObj->getAccessToken( );         
        $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$ACCESS_TOKEN";
        //$tempid = $this->module['config']['templateid']; /*新订阅消息 从前端提交模板id过来*/
        /*guest_kanfang \ guest_ask \ baobei_status  */
        $ret2 = pdo_fetch("select * from ".  tablename("kbwdl_config")." where uniacid='$uniacid' and placeid=61 and module='kbwdl_shequzufang'");
        $moban  =  iunserializer($ret2['conf_value']);
        switch ($form_id){
            case 'guest_kanfang':
                $form_id = $moban['guest_kanfang'];
                $sendbody = [
                    'thing5'=>['value'=> $data['keyword1']['value']],
                    'thing1'=> ['value'=> $data['keyword2']['value']],            
                ];
                break;
            case 'guest_ask':
                $form_id = $moban['guest_ask'];
                $sendbody = [
                    'phrase1'=>['value'=> '通过审核'],
                    'thing2'=> ['value'=> $data['keyword2']['value']], 
                    'date3'=>['value'=> date('Y年m月d日')],
                ];
                break;
            case 'baobei_status':
                $form_id = $moban['baobei_status'];
                $sendbody = [
                    'name1'=>['value'=>   $data['keyword2']['value'] ],
                    'phrase3'=>['value'=>str_replace( '经纪人客户：','',$data['keyword3']['value'][0] )]  , 
                    'phrase5'=>['value'=> $data['keyword4']['value']],
                    'phone_number2'=> ['value'=> str_replace('手机号：','',$data['keyword3']['value'][1] ) ],
                ];
                break;
            default:
                break;
        }
         
        $body = array('touser'=>$openid,'template_id'=>$form_id);
        if(!empty($page)){
            $body['page'] = $page;
        }
        $body['data'] = $sendbody; 
       
        /*array('keyword1'=>array('value'=>'预约看房'),'keyword2'=>array('value'=>'请及时处理'));*/
         load()->func('logging');
          logging_run($body);
         $ret =   ihttp_post($url, json_encode($body));
         logging_run($ret);
         return $ret;
    }   
}

